import {
  ALL,
  Body,
  Get,
  Inject,
  Post,
  Provide,
  Query,
  Validate,
} from '@midwayjs/decorator';
import { CreateApiDoc } from '@midwayjs/swagger';
import { Context } from 'egg';
import { CoolController, BaseController } from '@cool-midway/core';
import { GoodsInfoService } from '../../../goods/service/info';
import { UserFollowService } from '../../../user/service/follow';
import { UserInfoService } from '../../../user/service/info';
import { UserNotifyService } from '../../../user/service/notify';
import { WeiboTagsService } from '../../service/tags';
import { WeiboBlogService } from '../../service/weibo';
import { WeiboActivityService } from '../../service/activity';
import { WeiboCommentsService } from '../../service/comment';
import * as _ from 'lodash';
import { CreateWeiBoDTO } from '../../dto/weibo';
import { UserActionLogService } from '../../../user/service/log';

/**
 * 描述
 */
@Provide()
@CoolController()
export class AppWeiboBlogController extends BaseController {

  @Inject()
  blogSrv: WeiboBlogService;

  @Inject()
  blogTagsSrv: WeiboTagsService;

  @Inject()
  userSrv: UserInfoService;

  @Inject()
  userFollowService: UserFollowService;

  @Inject()
  goodsSrv: GoodsInfoService;

  @Inject()
  userActionLogSrv: UserActionLogService;

  @Inject()
  userNotifySrv: UserNotifyService;

  @Inject()
  activitySrv: WeiboActivityService;

  @Inject()
  weiboCommSrv: WeiboCommentsService;

  @Inject()
  ctx: Context;

  @CreateApiDoc().summary('发布图文').respond(200).build()
  @Post('/create')
  async create(@Body(ALL) query: CreateWeiBoDTO) {
    console.log('query---->', query);
    query.userId = this.ctx.user.id;
    query.ipAddr = await this.userActionLogSrv.getUserIpAddr(this.ctx.user.id);
    return this.ok(await this.blogSrv.create(query));
  }

  @CreateApiDoc()
    .summary('首页')
    .param('page', { required: true })
    .param('size', { required: true })
    .param('order', { required: true })
    .respond(200)
    .build()
  @Post('/index')
  @Validate()
  async home(@Body(ALL) query: any) {
    const topBannber = await this.blogSrv.top(0, 6);
    const hotTags = await this.blogTagsSrv.hot(0, 6);
    let { list } = await this.blogSrv.page(
      { ...query, isAudit: 1, type: ['grass', 'fap', 'creation'] },
      {}
    );
    if (this.ctx.user.id) {
      list = await this.blogSrv.transformInCollect(list, this.ctx.user.id);
      list = await this.blogSrv.transformInLove(list, this.ctx.user.id);
    }
    return this.ok({ topBannber, hotTags, list });
  }

  @CreateApiDoc().summary('分页查博客').respond(200).build()
  @Post('/page')
  async page(@Body(ALL) query: any) {
    query.userId = this.ctx.user?.id;
    query.isAudit = 1;
    const data = await this.blogSrv.page(query, {});
    data.list = await this.userSrv.transformInUser(data.list, 'user_id');
    const gIds = this.getGoods(data.list);
    data.list = await this.transformInGoods(data.list, gIds);
    data.list = await this.blogSrv.transformInCollect(
      data.list,
      this.ctx.user?.id
    );
    data.list = await this.blogSrv.transformInLove(
      data.list,
      this.ctx.user?.id
    );
    return this.ok(data);
  }

  @CreateApiDoc()
    .summary('相关推荐')
    .param('ids', { description: 'ids array tagId' })
    .param('page')
    .param('size')
    .respond(200)
    .build()
  @Post('/recommend')
  async recommend(@Body(ALL) query: any) {
    const { ids } = query;
    const data = await this.blogSrv.recommends(ids, query);
    
    data.list = await this.userSrv.transformInUser(data.list, 'user_id');
    data.list = await this.userFollowService.transformInFollow(
      data.list,
      this.ctx.user?.id,
      'user_id'
    );
    data.list = await this.blogSrv.transformInCollect(
      data.list,
      this.ctx.user?.id
    );
    data.list = await this.blogSrv.transformInLove(data.list, this.ctx.user?.id);
    data.list = await this.weiboCommSrv.findCommentListCount(data.list);
    const gIds = this.getGoods(data.list);
    data.list = await this.transformInGoods(data.list, gIds);
    return this.ok(data);
  }

  @CreateApiDoc()
    .summary('已赞')
    .param('ids', { description: 'ids array tagId' })
    .param('page')
    .param('size')
    .respond(200)
    .build()
  @Post('/inlove')
  async inLove(@Body(ALL) query: any) {
    const { id } = this.ctx.user;
    const data = await this.blogSrv.inLove(id, query);
    data.list = await this.userSrv.transformInUser(data.list, 'user_id');
    data.list = await this.userFollowService.transformInFollow(
      data.list,
      id,
      'user_id'
    );

    const gIds = this.getGoods(data.list);
    data.list = await this.transformInGoods(data.list, gIds);
    return this.ok(data);
  }

  @CreateApiDoc()
    .summary('已关注')
    .param('ids', { description: 'ids array tagId' })
    .param('page')
    .param('size')
    .respond(200)
    .build()
  @Post('/infollow')
  async inFollow(@Body(ALL) query: any) {
    const { id } = this.ctx.user;
    const data = await this.blogSrv.inFollow(id, query);
    data.list = await this.userSrv.transformInUser(data.list, 'user_id');
    data.list = await this.userFollowService.transformInFollow(
      data.list,
      id,
      'user_id'
    );

    const gIds = this.getGoods(data.list);
    data.list = await this.transformInGoods(data.list, gIds);
    return this.ok(data);
  }

  /**
   * 批量获取goods
   */
  async transformInGoods(arr: [any], ids) {
    if (!arr || !Array.isArray(arr)) return [];
    const goodsList = await this.goodsSrv.lists(ids);
    arr.map((v, k) => {
      arr[k]['goodsList'] = null;
      const goods = [];
      goodsList.map(item => {
        if (!_.isNull(v.goods)) {
          if (v.goods && v.goods.split(',').indexOf(item.id)) {
            goods.push(item);
          }
        }
      });
      arr[k]['goodsList'] = goods;
    });
    return arr;
  }

  getGoods(list) {
    const ids = [];
    if (!list || !Array.isArray(list)) return ids;
    list.map(v => {
      if (v.goods && v.goods.indexOf(',') > 0) {
        v.goods.split(',').map(id => {
          ids.push(parseInt(id));
        });
      }
    });
    return ids;
  }

  @CreateApiDoc()
    .summary('收藏')
    .param('id', { description: 'blogId' })
    .respond(200)
    .build()
  @Get('/collect')
  async Collect(@Query() id: number) {
    const data = await this.blogSrv.Collect(id, this.ctx.user.id);
    const blog = await this.blogSrv.info(id);
    this.userFollowService.upCount(
      this.ctx.user.id,
      blog.userId,
      'countCollects',
      data
    );
    // 存消息通知
    if (this.ctx.user.id != blog.userId && data == 'up') {
      this.userNotifySrv.save({
        type: 2, //1、公告 2、提醒 3、私信
        action: 5, // 1点赞 2评论 3回复 4关注 5收藏
        targetId: blog.id,
        senderId: this.ctx.user.id,
        userId: blog.userId,
      });
    }
    return this.ok(data);
  }

  @CreateApiDoc()
    .summary('点赞')
    .param('id', { description: 'blogId' })
    .respond(200)
    .build()
  @Get('/love')
  async love(@Query() id: number) {
    const data = await this.blogSrv.love(id, this.ctx.user.id);
    const blog = await this.blogSrv.info(id);
    this.userFollowService.upCount(
      this.ctx.user.id,
      blog.userId,
      'countLoves',
      data
    );
    // 存消息通知
    if (this.ctx.user.id != blog.userId && data == 'up') {
      this.userNotifySrv.save({
        type: 2, //1、公告 2、提醒 3、私信
        action: 1, // 1点赞 2评论 3回复 4关注
        targetId: blog.id,
        senderId: this.ctx.user.id,
        userId: blog.userId,
      });
    }
    return this.ok(data);
  }

  @CreateApiDoc()
    .summary('详情')
    .param('id', { description: 'blogId ｜ ids' })
    .respond(200)
    .build()
  @Get('/info')
  async info(@Query() id: any) {
    const blog = await this.blogSrv.info(id);
    console.log('blog===>', blog);

    const user = (await this.userSrv.info(blog.userId, [])) || {};

    // 是否登录
    const userId = this.ctx.user?.id;
    if (userId) {
      user['is_follow'] = await this.userFollowService.isFollow(
        blog.userId,
        userId
      );
      blog['is_collect'] = await this.blogSrv.hasConllect(blog.id, userId);
      blog['is_love'] = await this.blogSrv.hasLove(blog.id, userId);
    } else {
      user['is_follow'] = false;
      blog['is_collect'] = false;
      blog['is_love'] = false;
    }

    // 当前用户的属地
    user.ip_addr = await this.userActionLogSrv.getUserIpAddr(blog.userId);

    blog.user = user;

    if (blog.tags && blog.tags.indexOf(',') > 0) {
      blog.tagsIds = blog.tags;
      blog.tags = await this.blogTagsSrv.findInIds(blog.tags.split(','));
    }

    if (blog.goods && blog.goods.indexOf(',') > 0) {
      blog.goodsList = await this.goodsSrv.lists(blog.goods.split(','));
    }

    if (blog.activity && blog.activity.indexOf(',') > 0) {
      blog.activityList = await this.activitySrv.findInIds(
        blog.activity.split(',')
      );
    }

    // 前端统一字段
    blog.count_comment = await this.weiboCommSrv.findCommentCount(id);
    blog.count_collect = blog.countCollect;
    blog.count_view = blog.countView;
    blog.count_love = blog.countLove;
    blog.ip_addr = blog.ipAddr;
    delete blog.ipAddr;
    delete blog.countComment;
    delete blog.countCollect;
    delete blog.countView;
    delete blog.countLove;
    return this.ok(blog);
  }

}
